@using System.Text.Json
@using System.Web
@using MeiwenDiaryWeb.Models
@inject SwalService _swalService

<h3>@SummaryViewModel.SinceYear / @SummaryViewModel.SinceMonth / @SummaryViewModel.SinceDayOfMonth - @SummaryViewModel.ToYear / @SummaryViewModel.ToMonth / @SummaryViewModel.ToDayOfMonth</h3>

@if (SummaryViewModel.Id == -1) {
    <span>尚未生成回顾</span>
    <p>
        <LinkButton Color="Color.None" OnClick="GenerateAsync">生成回顾
        </LinkButton>
    </p>
} else {
    @(new MarkupString(HttpUtility.HtmlEncode(SummaryViewModel.Content).Replace(Environment.NewLine, "<br />")))
    <p>
        <LinkButton Color="Color.None" OnClick="EditAsync">编辑</LinkButton>
        <PopConfirmButton ConfirmButtonColor="Color.Danger"
                          Content="确定要删除么？"
                          CloseButtonText="关闭" ConfirmButtonText="确定"
                          OnConfirm="DeleteAsync">删除
        </PopConfirmButton>
        <LinkButton Color="Color.None" OnClick="GenerateAsync">重新生成回顾
        </LinkButton>
    </p>
}

@if (_isGenerating) {
    <Progress IsAnimated="true" IsStriped="true" Value="100"></Progress>
}

<Modal @ref="_editModal">
    <ModalDialog ShowSaveButton="true" OnSaveAsync="SaveAsync"
                 CloseButtonText="关闭" SaveButtonText="保存">
        <BodyTemplate>
            <Textarea @bind-Value="@SummaryViewModel.Content"
                      rows="10"></Textarea>
        </BodyTemplate>
    </ModalDialog>
</Modal>

@code {
    [Parameter] public SummaryViewModel SummaryViewModel { get; set; }

    private bool _isGenerating;

    private Modal _editModal;

    private async Task EditAsync() => await _editModal.Show();

    private async Task GenerateAsync() {
        _isGenerating = true;
        StateHasChanged();

        using var httpClient = new HttpClient();
        var jsonContent = JsonContent.Create(new {
            SummaryViewModel.SinceYear,
            SummaryViewModel.SinceMonth,
            SummaryViewModel.SinceDayOfMonth,
            SummaryViewModel.ToYear,
            SummaryViewModel.ToMonth,
            SummaryViewModel.ToDayOfMonth
        }, options: new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
        await jsonContent.ReadAsStringAsync();

        HttpResponseMessage response;
        try {
            response = await httpClient.PostAsync("http://localhost:35210/summaries/generate", jsonContent);
            response.EnsureSuccessStatusCode();
        } catch (Exception e) {
            await _swalService.Show(new SwalOption { Content = e.Message, Category = SwalCategory.Error });
            _isGenerating = false;
            StateHasChanged();
            return;
        }

        var content = await response.Content.ReadAsStringAsync();
        SummaryViewModel = JsonSerializer.Deserialize<SummaryViewModel>(content, options: new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!;
        _isGenerating = false;
        StateHasChanged();
    }

    private async Task DeleteAsync() {
        using var httpClient = new HttpClient();
        try {
            var response = await httpClient.DeleteAsync("http://localhost:35210/summaries/" + SummaryViewModel.Id);
            response.EnsureSuccessStatusCode();
        } catch (Exception e) {
            await _swalService.Show(new SwalOption { Content = e.Message, Category = SwalCategory.Error });
            return;
        }

        SummaryViewModel.Id = -1;
        SummaryViewModel.Content = null;
        StateHasChanged();

        await _swalService.Show(new SwalOption { Content = "回顾已删除", Category = SwalCategory.Success });
    }

    private async Task<bool> SaveAsync() {
        using var httpClient = new HttpClient();
        var jsonContent = JsonContent.Create(new { SummaryViewModel.Content }, options: new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
        await jsonContent.ReadAsStringAsync(); // magic code to make it run but why?

        try {
            var response = await httpClient.PutAsync("http://localhost:35210/summaries/" + SummaryViewModel.Id, jsonContent);
            response.EnsureSuccessStatusCode();
        } catch (Exception e) {
            await _swalService.Show(new SwalOption { Content = e.Message, Category = SwalCategory.Error });
            return false;
        }

        await _swalService.Show(new SwalOption { Content = "回顾已保存", Category = SwalCategory.Success });
        return true;
    }

}